import React, {Component} from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';
import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
import tabsRouter from './router/tabsRouter';
import routers from './router/routers';
import {connect} from 'react-redux';
import {View, Text, TouchableOpacity, StyleSheet, Platform} from 'react-native';
import Icon from '$/components/Icon'
import backPress from '$/utils/backPress'
import NavUtils from '$/utils/NavUtils';
import RNExitApp from 'react-native-exit-app';
import {Toast} from 'antd-mobile-rn';

const Tab = createBottomTabNavigator();
const Stack = createStackNavigator();


function TabBar(props) {
    const { state, descriptors, navigation, app } = props;
    return (
        <View style={[styles.tabBox, {
            backgroundColor: app.backgroundColor
        }]}>
            {state.routes.map((route, index) => {
                const { options } = descriptors[route.key];
                const label =
                    options.tabBarLabel !== undefined
                        ? options.tabBarLabel
                        : options.title !== undefined
                        ? options.title
                        : route.name;

                const isFocused = state.index === index;

                const onPress = () => {
                    const event = navigation.emit({
                        type: 'tabPress',
                        target: route.key,
                        canPreventDefault: true,
                    });

                    if (!isFocused && !event.defaultPrevented) {
                        navigation.navigate(route.name);
                    }
                };

                const onLongPress = () => {
                    navigation.emit({
                        type: 'tabLongPress',
                        target: route.key,
                    });
                };

                return (
                    <TouchableOpacity
                        key={route.key}
                        accessibilityRole="button"
                        accessibilityStates={isFocused ? ['selected'] : []}
                        accessibilityLabel={options.tabBarAccessibilityLabel}
                        testID={options.tabBarTestID}
                        onPress={onPress}
                        onLongPress={onLongPress}
                        style={styles.tabItem}
                        activeOpacity={0.85}
                    >
                        <Icon style={{top: 2}} color={isFocused ? app.color : '#888'} size={23}>{options.icon}</Icon>
                        <Text style={[{ color: isFocused ? app.color : '#888' }, styles.tabFont]}>{label}</Text>
                    </TouchableOpacity>
                );
            })}
        </View>
    );
}
const TabBars = connect(({ app }) => ({ app }))(TabBar);


const isAndroid = Platform.OS === 'android';
let pressIndex = 1;
let passRoute = ['TabBar'];
class TabBarCom extends Component{
    componentDidMount(): void {
        //监听安卓返回事件
        if(isAndroid){
            //添加需要执行退出应用操作的路由
            tabsRouter.map(({name}) => passRoute.push(name));
            backPress.createBackPress(() => {
                let route = NavUtils.routers[NavUtils.routers.length - 1];
                if(passRoute.includes(route)){
                    if(pressIndex < 2){
                        pressIndex++;
                        Toast.info('再按一次退出应用', 0.5, () => {}, false);
                        let timer = setTimeout(() => {
                            pressIndex = 1;
                            clearTimeout(timer)
                        }, 2000)
                        return true
                    }else{
                        RNExitApp.exitApp()
                    }
                }else{
                    NavUtils.routers.pop();
                    return false
                }
            })
            //执行事件
            backPress.didMountBackPress()
        }
    }

    render(){
        return (
            <Tab.Navigator tabBar={props => <TabBars {...props} />}>
                {tabsRouter.map(item => (
                    <Tab.Screen
                        options={{ icon: item.icon, title: item.title}}
                        key={item.name}
                        name={item.name}
                        component={item.component}
                    />
                ))}
            </Tab.Navigator>
        )
    }
}

class TabBox extends Component {
    render() {
        const {app} = this.props;
        const screenOpt = {
            headerStyle: {
                backgroundColor: app.color,
            },
            headerTintColor: app.fontColor,
            headerMode: 'screen',
            header: () => null
        }
        return (
            <NavigationContainer>
                <Stack.Navigator initialRouteName={'Welcome'} screenOptions={screenOpt}>
                    <Stack.Screen  name="TabBar" component={TabBarCom}/>
                    {routers.map(item => (
                        <Stack.Screen
                            key={item.name}
                            name={item.name}
                            component={item.component}
                            initialParams={{title: item.title}}
                        />
                    ))}
                </Stack.Navigator>
            </NavigationContainer>
        );
    }
}

export default connect(({ app }) => ({ app }))(TabBox);

const styles = StyleSheet.create({
    tabBox:{
        flexDirection: 'row' ,
        justifyContent: 'center',
        height: 50,
        backgroundColor: '#fff',
        borderTopWidth: 1,
        borderTopColor: '#eee',
        paddingBottom: 2,
        opacity: 0.95
    },
    tabItem:{
        flex: 1,
        flexDirection: 'column',
        alignItems: 'center'
    },
    tabFont:{
        fontSize: 12
    }
})

